package springinpractice.r4_1.web;

import java.util.logging.Logger;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import springinpractice.r4_1.model.User;

/*
 * Author       :       Willie Wheeler and John Wheeler
 * Book         :       'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */

@Controller
@RequestMapping("/register/form.htm")
public class RegFormController
{
	private static final String MA_USER = "user";

	@RequestMapping(method = RequestMethod.GET)
	public void form(Model model)
	{
		model.addAttribute(MA_USER, new User());
	}

	@RequestMapping(method = RequestMethod.POST)
	public String form(@ModelAttribute(MA_USER) User user, BindingResult result)
	{
		verifyBinding(result);
		Logger.global.info("Processing user: " + user);
		return "redirect:confirm.htm";
	}

	@InitBinder
	public void initBinder(WebDataBinder binder)
	{
		binder.setAllowedFields(new String[] { "firstName", "lastName",
				"email", "username", "password", "passwordConfirmation",
				"marketingOk", "acceptTerms" });
	}

	private void verifyBinding(BindingResult result)
	{
		String[] suppressedFields = result.getSuppressedFields();
		if (suppressedFields.length > 0)
		{
			throw new RuntimeException(
					"You've attempted to bind fields that haven't been allowed in initBinder(): "
							+ StringUtils.join(suppressedFields, ", "));
		}
	}
}
